package com.nuc.seckill.controller;

import com.nuc.seckill.base.CommonQueryBean;
import com.nuc.seckill.enums.ProductsEnum;
import com.nuc.seckill.model.SeckillProducts;
import com.nuc.seckill.service.ProductsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author spider
 */
@Controller
@RequestMapping(value = "/product")
@Slf4j
public class SeckillProductsController {

    @Resource
    private ProductsService productsService;

    /**
     * 分页展示相关的界面.
     */
    @RequestMapping("/listPageProducts")
    public String listPageSeckillProducts(Model model, String name,
                                          @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                          @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {

        SeckillProducts searchItem = new SeckillProducts();
        if (StringUtils.isNotEmpty(name)) {
            searchItem.setName(name);
            model.addAttribute("name", name);
        }

        CommonQueryBean queryBean = new CommonQueryBean();
        queryBean.setPageSize(pageSize);
        queryBean.setStart((pageNum - 1) * pageSize);
        List<SeckillProducts> productsList = productsService.list4Page(searchItem, queryBean);

        long total = productsService.count(searchItem);
        int totalPageNum = (int) total / pageSize;
        if (total % pageSize > 0) {
            totalPageNum++;
        }

        model.addAttribute("total", total);
        model.addAttribute("totalPage", totalPageNum);
        model.addAttribute("list", productsList);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("pageNum", pageNum);

        return "product/listPageProducts";
    }

    /**
     * 输入创建product元素的界面.
     */
    @RequestMapping("/beforeCreateProduct")
    public String beforeCreateProduct() {
        return "product/beforeCreateProduct";
    }

    @RequestMapping("/doCreateProduct")
    public String doCreateProduct(String uniqueId, String name,
                                  String startBuyTimeStr, Integer amount, String desc) throws Exception {
        Assert.notNull(uniqueId, "uniqueId is not null");
        Assert.notNull(name, "name is not null");
        Assert.notNull(startBuyTimeStr, "startBuyTimeStr is not null");
        Assert.notNull(amount, "amount is not null");

        SeckillProducts products = new SeckillProducts();
        products.setName(name);
        products.setStartBuyTime(DateUtils.parseDate(startBuyTimeStr, "yyyy-MM-dd HH:mm:SS"));
        products.setCount(amount);
        products.setProductPeriodKey(uniqueId);
        if (StringUtils.isNotEmpty(desc)) {
            products.setProductDesc(desc);
        }

        productsService.uniqueInsert(products);

        return "redirect:listPageProducts?isSave=yes";
    }

    /**
     * 进入更新product的界面.
     */
    @RequestMapping("/beforeUpdateProduct")
    public String beforeUpdateProduct(Model model, Long id) {

        SeckillProducts products = productsService.selectByPrimaryKey(id);
        if (products != null) {
            model.addAttribute("item", products);
        }

        return "product/beforeUpdateProduct";
    }

    /**
     * 实际创建或更新product的业务逻辑.
     */
    @RequestMapping("/doUpdateProduct")
    public String doUpdateProduct(Long id, String name,
                                  String startBuyTimeStr, Integer amount, String desc) throws Exception {
        SeckillProducts products = productsService.selectByPrimaryKey(id);

        if (StringUtils.isNotEmpty(name)) {
            products.setName(name);
        }
        if (StringUtils.isNotEmpty(startBuyTimeStr)) {
            products.setStartBuyTime(DateUtils.parseDate(startBuyTimeStr, "yyyy-MM-dd HH:mm:SS"));
        }
        if (amount != null) {
            products.setCount(amount);
        }
        if (StringUtils.isNotEmpty(desc)) {
            products.setProductDesc(desc);
        }
        products.setUpdatedTime(new Date());

        productsService.updateByPrimaryKeySelective(products);

        return "redirect:listPageProducts";
    }

    /**
     * 查看product的元素信息，详情页面中所有元素都展示.
     */
    @RequestMapping("/showProductItem")
    public String showProductItem(Model model, Long id) {

        SeckillProducts products = productsService.selectByPrimaryKey(id);
        if (products != null) {
            model.addAttribute("item", products);
        }

        return "product/showProductItem";
    }

    /**
     * 更新productStatus状态.
     */
    @RequestMapping("/updateProductStatus")
    public String updateProductStatus(Long id, Integer status) {

        SeckillProducts products = productsService.selectByPrimaryKey(id);
        products.setStatus(status);
        //模拟逻辑删除又修改回来，就不额外添加方法了
        if (ProductsEnum.STATUS_IS_ONLINE.getValue().equals(status) && ProductsEnum.IS_DELETED.getValue().equals(products.getIsDeleted())) {
            products.setIsDeleted(0);
        }
        products.setUpdatedTime(new Date());
        productsService.updateByPrimaryKeySelective(products);

        return "redirect:listPageProducts";
    }

    /**
     * 逻辑删除相关的秒杀product信息.
     */
    @RequestMapping("/deleteProduct")
    public String deleteProduct(Long id) {
        //不直接使用物理删除，改成更新isDeleted字段，改成逻辑update
        SeckillProducts products = productsService.selectByPrimaryKey(id);
        products.setIsDeleted(ProductsEnum.IS_DELETED.getValue());
        products.setUpdatedTime(new Date());
        productsService.updateByPrimaryKeySelective(products);

        return "redirect:listPageProducts";
    }


}
